import React from 'react';
import { Form, Radio, Select, InputNumber, Modal, Spin } from 'antd';
import { getBaseRuleInfo, saveBaseRuleInfo } from '../../services';
import styles from './BasicRule.less';

const { Option } = Select;
const { confirm } = Modal;

const BasicRule = ({ form }, parentRef) => {
    const { getFieldDecorator } = form;
    const [info, setInfo] = React.useState({ id: '' });
    const [loading, setLoading] = React.useState(false);
    const [audit, setAudit] = React.useState(0);
    const [accept, setAccept] = React.useState(0);
    const [autoAudit, setAutoAudit] = React.useState(0);
    const [autoAccept, setAutoAccept] = React.useState(0);
    const [autoExecuteStart, setAutoExecuteStart] = React.useState(0);
    const [autoExecuteEnd, setAutoExecuteEnd] = React.useState(0);

    const getBaseRule = async () => {
        setLoading(true);
        const res = await getBaseRuleInfo();
        // console.log(res);
        const { code, data } = res;
        if (code === 10000 && data && data.id) {
            // console.log(data);
            const {
                auditEndTimeSwitchFlag,
                acceptanceEndTimeSwitchFlag,
                auditToUrgeSwitchFlag,
                acceptanceToUrgeSwitchFlag,
                executeToUrgeSwitchFlag,
                planEndToUrgeSwitchFlag,
                auditEndTimeDayLimit,
                auditEndTimePassType,
                acceptanceEndTimeDayLimit,
                acceptanceEndTimePassType,
                auditToUrgeHourLater,
                auditToUrgePeriodHourLimit,
                auditToUrgePeriodTerminatedLimit,
                acceptanceToUrgeHourLater,
                acceptanceToUrgePeriodHourLimit,
                acceptanceToUrgePeriodTerminatedLimit,
                executeToUrgePeriodHourLimit,
                executeToUrgePeriodTerminatedLimit,
                planEndHourLater,
                planEndToUrgePeriodHourLimit,
                planEndToUrgePeriodTerminatedLimit
            } = data;
            setInfo(data);
            setAudit(auditEndTimeSwitchFlag);
            setAccept(acceptanceEndTimeSwitchFlag);
            setAutoAudit(auditToUrgeSwitchFlag);
            setAutoAccept(acceptanceToUrgeSwitchFlag);
            setAutoExecuteStart(executeToUrgeSwitchFlag);
            setAutoExecuteEnd(planEndToUrgeSwitchFlag);
            if (auditEndTimeSwitchFlag) {
                form.setFieldsValue({
                    auditTime: auditEndTimeDayLimit,
                    auditPass: auditEndTimePassType
                });
            }
            if (acceptanceEndTimeSwitchFlag) {
                form.setFieldsValue({
                    acceptTime: acceptanceEndTimeDayLimit,
                    acceptPass: acceptanceEndTimePassType
                });
            }
            if (auditToUrgeSwitchFlag) {
                form.setFieldsValue({
                    auditDelay: auditToUrgeHourLater,
                    auditInterval: auditToUrgePeriodHourLimit,
                    auditCount: auditToUrgePeriodTerminatedLimit
                });
            }
            if (acceptanceToUrgeSwitchFlag) {
                form.setFieldsValue({
                    acceptDelay: acceptanceToUrgeHourLater,
                    acceptInterval: acceptanceToUrgePeriodHourLimit,
                    acceptCount: acceptanceToUrgePeriodTerminatedLimit
                });
            }
            if (executeToUrgeSwitchFlag) {
                form.setFieldsValue({
                    executeStartInterval: executeToUrgePeriodHourLimit,
                    executeStartCount: executeToUrgePeriodTerminatedLimit
                });
            }
            if (planEndToUrgeSwitchFlag) {
                form.setFieldsValue({
                    executeEndDelay: planEndHourLater,
                    executeEndInterval: planEndToUrgePeriodHourLimit,
                    executeEndCount: planEndToUrgePeriodTerminatedLimit
                });
            }
        }
        setLoading(false);
    };

    const saveBaseRule = async params => {
        setLoading(true);
        const res = await saveBaseRuleInfo(params);
        // console.log(res);
        const { code } = res;
        if (code === 10000) {
            getBaseRule();
            return;
        }
        setLoading(false);
    };

    React.useImperativeHandle(parentRef, () => ({
        save() {
            form.validateFields(
                ['auditEndTime', 'acceptEndTime', 'auditAuto', 'acceptAuto', 'executeStartAuto', 'executeEndAuto'],
                { force: true },
                err => {
                    if (err) {
                        return;
                    }
                    const params = form.getFieldsValue();
                    // console.log(params);
                    const {
                        auditTime,
                        auditPass,
                        acceptTime,
                        acceptPass,
                        auditDelay,
                        auditInterval,
                        auditCount,
                        acceptDelay,
                        acceptInterval,
                        acceptCount,
                        executeStartInterval,
                        executeStartCount,
                        executeEndDelay,
                        executeEndInterval,
                        executeEndCount
                    } = params;
                    const auditObj = {
                        auditEndTimeSwitchFlag: audit
                    };
                    if (audit) {
                        auditObj.auditEndTimeDayLimit = auditTime;
                        auditObj.auditEndTimePassType = auditPass;
                    }
                    const acceptObj = {
                        acceptanceEndTimeSwitchFlag: accept
                    };
                    if (accept) {
                        acceptObj.acceptanceEndTimeDayLimit = acceptTime;
                        acceptObj.acceptanceEndTimePassType = acceptPass;
                    }
                    const auditToUrgeObj = {
                        auditToUrgeSwitchFlag: autoAudit
                    };
                    if (autoAudit) {
                        auditToUrgeObj.auditToUrgeHourLater = auditDelay;
                        auditToUrgeObj.auditToUrgePeriodHourLimit = auditInterval;
                        auditToUrgeObj.auditToUrgePeriodTerminatedLimit = auditCount;
                    }
                    const acceptanceToUrgeObj = {
                        acceptanceToUrgeSwitchFlag: autoAccept
                    };
                    if (autoAccept) {
                        acceptanceToUrgeObj.acceptanceToUrgeHourLater = acceptDelay;
                        acceptanceToUrgeObj.acceptanceToUrgePeriodHourLimit = acceptInterval;
                        acceptanceToUrgeObj.acceptanceToUrgePeriodTerminatedLimit = acceptCount;
                    }
                    const executeToUrgeObj = {
                        executeToUrgeSwitchFlag: autoExecuteStart
                    };
                    if (autoExecuteStart) {
                        executeToUrgeObj.executeToUrgePeriodHourLimit = executeStartInterval;
                        executeToUrgeObj.executeToUrgePeriodTerminatedLimit = executeStartCount;
                    }
                    const planEndToUrgeObj = {
                        planEndToUrgeSwitchFlag: autoExecuteEnd
                    };
                    if (autoExecuteEnd) {
                        planEndToUrgeObj.planEndHourLater = executeEndDelay;
                        planEndToUrgeObj.planEndToUrgePeriodHourLimit = executeEndInterval;
                        planEndToUrgeObj.planEndToUrgePeriodTerminatedLimit = executeEndCount;
                    }
                    const { id = '' } = info;
                    const finalParams = {
                        id,
                        ...auditObj,
                        ...acceptObj,
                        ...auditToUrgeObj,
                        ...acceptanceToUrgeObj,
                        ...executeToUrgeObj,
                        ...planEndToUrgeObj
                    };
                    // console.log(finalParams);
                    saveBaseRule(finalParams);
                }
            );
        }
    }));

    const titleStyle = {
        fontSize: 16,
        color: '#000',
        padding: '12px 0 12px'
    };

    const handleRadioChange = (e, type) => {
        // console.log('radio checked', e.target.value);
        confirm({
            title: `确定切换为${e.target.value ? '限制' : '不限制'}？`,
            onOk() {
                // console.log('OK');
                if (type === 'audit') {
                    setAudit(e.target.value);
                    if (!e.target.value) {
                        setTimeout(() => {
                            form.validateFields(['auditEndTime'], { force: true });
                        }, 10);
                    }
                } else if (type === 'accept') {
                    setAccept(e.target.value);
                    if (!e.target.value) {
                        setTimeout(() => {
                            form.validateFields(['acceptEndTime'], { force: true });
                        }, 10);
                    }
                } else if (type === 'autoAudit') {
                    setAutoAudit(e.target.value);
                    if (!e.target.value) {
                        setTimeout(() => {
                            form.validateFields(['auditAuto'], { force: true });
                        }, 10);
                    }
                } else if (type === 'autoAccept') {
                    setAutoAccept(e.target.value);
                    if (!e.target.value) {
                        setTimeout(() => {
                            form.validateFields(['acceptAuto'], { force: true });
                        }, 10);
                    }
                } else if (type === 'autoExecuteStart') {
                    setAutoExecuteStart(e.target.value);
                    if (!e.target.value) {
                        setTimeout(() => {
                            form.validateFields(['executeStartAuto'], { force: true });
                        }, 10);
                    }
                } else if (type === 'autoExecuteEnd') {
                    setAutoExecuteEnd(e.target.value);
                    if (!e.target.value) {
                        setTimeout(() => {
                            form.validateFields(['executeEndAuto'], { force: true });
                        }, 10);
                    }
                }
            }
        });
    };

    const handleValidate = type => {
        form.validateFields([type]);
    };

    const renderInput = (paramName, formItemName, initialValue, max = 99999) => (
        <Form.Item>
            {getFieldDecorator(paramName, {
                initialValue
            })(
                <InputNumber
                    min={1}
                    max={max}
                    precision={0}
                    style={{ width: 75 }}
                    onBlur={() => handleValidate(formItemName)}
                />
            )}
        </Form.Item>
    );

    React.useEffect(() => {
        getBaseRule();
    }, []);

    return (
        <Form layout="inline" style={{ marginBottom: 80 }}>
            <Spin spinning={loading}>
                <div style={titleStyle}>截止时间配置</div>
                <div className={styles.formRow}>
                    <Form.Item label="人工审核截止时间" required>
                        {getFieldDecorator('auditEndTime', {
                            rules: [
                                {
                                    validator: async () => {
                                        const { auditTime } = form.getFieldsValue();
                                        // console.log(audit);
                                        if (audit === 1 && !auditTime) {
                                            throw new Error('请输入人工审核截止时间');
                                        }
                                    }
                                }
                            ]
                        })(
                            <>
                                <Radio.Group
                                    style={{ width: 160 }}
                                    onChange={e => handleRadioChange(e, 'audit')}
                                    value={audit}
                                >
                                    <Radio value={0}>不限制</Radio>
                                    <Radio value={1}>限制</Radio>
                                </Radio.Group>
                            </>
                        )}
                    </Form.Item>
                    {!!audit && (
                        <>
                            从可开始审核节点的第
                            <Form.Item>
                                {getFieldDecorator('auditTime', {
                                    initialValue: 5
                                })(
                                    <InputNumber
                                        min={1}
                                        max={99999}
                                        precision={0}
                                        style={{ width: 75 }}
                                        onBlur={() => {
                                            form.validateFields(['auditEndTime']);
                                        }}
                                    />
                                )}
                            </Form.Item>
                            个自然日后算逾期审核，系统将自动审核
                            <Form.Item>
                                {getFieldDecorator('auditPass', {
                                    initialValue: 2
                                })(
                                    <Select style={{ width: 100 }}>
                                        <Option value={2}>不通过</Option>
                                        <Option value={1}>通过</Option>
                                    </Select>
                                )}
                            </Form.Item>
                        </>
                    )}
                </div>
                <div className={styles.formRow}>
                    <Form.Item label="人工验收截止时间" required>
                        {getFieldDecorator('acceptEndTime', {
                            rules: [
                                {
                                    validator: async () => {
                                        const { acceptTime } = form.getFieldsValue();
                                        if (accept === 1 && !acceptTime) {
                                            throw new Error('请输入人工验收截止时间');
                                        }
                                    }
                                }
                            ]
                        })(
                            <>
                                <Radio.Group
                                    style={{ width: 160 }}
                                    onChange={e => handleRadioChange(e, 'accept')}
                                    value={accept}
                                >
                                    <Radio value={0}>不限制</Radio>
                                    <Radio value={1}>限制</Radio>
                                </Radio.Group>
                            </>
                        )}
                    </Form.Item>
                    {!!accept && (
                        <>
                            从可开始验收节点的第
                            <Form.Item>
                                {getFieldDecorator('acceptTime', {
                                    initialValue: 5
                                })(
                                    <InputNumber
                                        min={1}
                                        max={99999}
                                        precision={0}
                                        style={{ width: 75 }}
                                        onBlur={() => {
                                            form.validateFields(['acceptEndTime']);
                                        }}
                                    />
                                )}
                            </Form.Item>
                            个自然日后算逾期验收，系统将自动验收
                            <Form.Item>
                                {getFieldDecorator('acceptPass', {
                                    initialValue: 1
                                })(
                                    <Select style={{ width: 100 }}>
                                        <Option value={2}>不通过</Option>
                                        <Option value={1}>通过</Option>
                                    </Select>
                                )}
                            </Form.Item>
                        </>
                    )}
                </div>
                <div style={titleStyle}>自动催办配置</div>
                <div className={styles.formRow}>
                    <Form.Item label="人工审核自动催办时间" required>
                        {getFieldDecorator('auditAuto', {
                            rules: [
                                {
                                    validator: async () => {
                                        const { auditDelay, auditInterval, auditCount } = form.getFieldsValue();
                                        if (autoAudit === 1 && !(auditDelay && auditInterval && auditCount)) {
                                            throw new Error('请输入人工审核自动催办时间');
                                        }
                                    }
                                }
                            ]
                        })(
                            <>
                                <Radio.Group
                                    style={{ width: 160 }}
                                    onChange={e => handleRadioChange(e, 'autoAudit')}
                                    value={autoAudit}
                                >
                                    <Radio value={0}>不限制</Radio>
                                    <Radio value={1}>限制</Radio>
                                </Radio.Group>
                            </>
                        )}
                        {!!autoAudit && (
                            <>
                                从可开始审核节点的第
                                {renderInput('auditDelay', 'auditAuto', 5)}
                                个小时后；每隔
                                {renderInput('auditInterval', 'auditAuto', 5)}
                                个小时重复推送提醒
                                {renderInput('auditCount', 'auditAuto', 3, 999)}
                                次后停止提醒；
                            </>
                        )}
                    </Form.Item>
                </div>
                <div className={styles.formRow}>
                    <Form.Item label="人工验收自动催办时间" required>
                        {getFieldDecorator('acceptAuto', {
                            rules: [
                                {
                                    validator: async () => {
                                        const { acceptDelay, acceptInterval, acceptCount } = form.getFieldsValue();
                                        if (autoAccept === 1 && !(acceptDelay && acceptInterval && acceptCount)) {
                                            throw new Error('请输入人工验收自动催办时间');
                                        }
                                    }
                                }
                            ]
                        })(
                            <>
                                <Radio.Group
                                    style={{ width: 160 }}
                                    onChange={e => handleRadioChange(e, 'autoAccept')}
                                    value={autoAccept}
                                >
                                    <Radio value={0}>不限制</Radio>
                                    <Radio value={1}>限制</Radio>
                                </Radio.Group>
                            </>
                        )}
                        {!!autoAccept && (
                            <>
                                从可开始验收节点的第
                                {renderInput('acceptDelay', 'acceptAuto', 5)}
                                个小时后；每隔
                                {renderInput('acceptInterval', 'acceptAuto', 5)}
                                个小时重复推送提醒
                                {renderInput('acceptCount', 'acceptAuto', 3, 999)}
                                次后停止提醒；
                            </>
                        )}
                    </Form.Item>
                </div>
                <div className={styles.formRow}>
                    <Form.Item label="人工执行开始催办时间" required>
                        {getFieldDecorator('executeStartAuto', {
                            rules: [
                                {
                                    validator: async () => {
                                        const { executeStartInterval, executeStartCount } = form.getFieldsValue();
                                        if (autoExecuteStart === 1 && !(executeStartInterval && executeStartCount)) {
                                            throw new Error('请输入人工执行开始催办时间');
                                        }
                                    }
                                }
                            ]
                        })(
                            <>
                                <Radio.Group
                                    style={{ width: 160 }}
                                    onChange={e => handleRadioChange(e, 'autoExecuteStart')}
                                    value={autoExecuteStart}
                                >
                                    <Radio value={0}>不限制</Radio>
                                    <Radio value={1}>限制</Radio>
                                </Radio.Group>
                            </>
                        )}
                        {!!autoExecuteStart && (
                            <>
                                超过开始时间后且状态依旧为待开始时；每隔
                                {renderInput('executeStartInterval', 'executeStartAuto', 5)}
                                个小时重复推送提醒
                                {renderInput('executeStartCount', 'executeStartAuto', 3, 999)}
                                次后停止提醒；
                            </>
                        )}
                    </Form.Item>
                </div>
                <div className={styles.formRow}>
                    <Form.Item label="人工执行完成前催办时间" required>
                        {getFieldDecorator('executeEndAuto', {
                            rules: [
                                {
                                    validator: async () => {
                                        const {
                                            executeEndDelay,
                                            executeEndInterval,
                                            executeEndCount
                                        } = form.getFieldsValue();
                                        if (
                                            autoExecuteEnd === 1 &&
                                            !(executeEndDelay && executeEndInterval && executeEndCount)
                                        ) {
                                            throw new Error('请输入人工执行完成前催办时间');
                                        }
                                    }
                                }
                            ]
                        })(
                            <>
                                <Radio.Group
                                    style={{ width: 160 }}
                                    onChange={e => handleRadioChange(e, 'autoExecuteEnd')}
                                    value={autoExecuteEnd}
                                >
                                    <Radio value={0}>不限制</Radio>
                                    <Radio value={1}>限制</Radio>
                                </Radio.Group>
                            </>
                        )}
                        {!!autoExecuteEnd && (
                            <>
                                任务截止时间前
                                {renderInput('executeEndDelay', 'executeEndAuto', 5)}
                                个小时；每隔
                                {renderInput('executeEndInterval', 'executeEndAuto', 1)}
                                个小时重复推送提醒
                                {renderInput('executeEndCount', 'executeEndAuto', 1, 999)}
                                次后停止提醒；
                            </>
                        )}
                    </Form.Item>
                </div>
            </Spin>
        </Form>
    );
};

export default Form.create()(React.forwardRef(BasicRule));
